package com.lnsoft.cac.server.handle.codec.frameMessage;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.NonNull;

import java.lang.reflect.Array;
import java.util.Arrays;

import static com.lnsoft.cac.server.handle.codec.frameMessage.Util.byteArrToString;

@Data
/**
 * 配置/状态交互---装置所属CAC信息查询/设置
 * */
public class Cfg_CACSub_Cfm {
    private int Command_Status;                     //1 byte         数据发送状态：①0xFF成功②0x00失败
    private int Request_Flag;                       //1 byte         标识位：标识选择请求或设置的参数，字节位自低向高依次对应9-11的各选择请求或设置的参数项
    private String CAC_IP;                             //4 byte         CACIP地址
    private String CAC_PORT;                           //2 byte         CAC 网络端口号
    private String Call_Centor;                     //20 byte        CAC电话号码（字符串）


//    public ByteBuf toByteBuf() throws Exception{
//        if (Command_Status != (byte)0xFF && Command_Status != (byte)0x00) {
//            throw new Exception("数据发送状态设置异常");
//        }
//
//        if (Call_Centor == null) {
//            Call_Centor = new byte[20];
//        }
//        if (Call_Centor.length != 20) {
//            throw new Exception("CAC电话号码设置异常");
//        }
//        ByteBuf bf = Unpooled.buffer(28);
//        bf.writeByte(Command_Status);
//        bf.writeByte(Request_Flag);
//        bf.writeInt(CAC_IP);
//        bf.writeShort(CAC_PORT);
//        bf.writeBytes(Call_Centor);
//        return bf;
//    }


    //  解析 { 配置/状态交互---装置所属CAC信息查询/设置 - 确认 } 帧报文内容区 到消息体中
    public static Cfg_CACSub_Cfm decFrameBody(@NonNull byte[] frameBody) throws Exception {
        ByteBuf bf = Unpooled.wrappedBuffer(frameBody);
        Cfg_CACSub_Cfm msg = new Cfg_CACSub_Cfm();
        int len = frameBody.length;
        if (len == 0) {
            return null;
        }
        if (len != 28) {
            throw new Exception("frameBody 数据异常");
        }
        msg.setCommand_Status(bf.getByte(0) & 0xFF);

        msg.setRequest_Flag(bf.getByte(1) & 0xFF);

        StringBuilder sb = new StringBuilder();
        sb.append(bf.getByte(2) & 0xFF).append(".");
        sb.append(bf.getByte(3) & 0xFF).append(".");
        sb.append(bf.getByte(4) & 0xFF).append(".");
        sb.append(bf.getByte(5) & 0xFF);
        msg.setCAC_IP(sb.toString());

        msg.setCAC_PORT(Integer.toString(bf.getUnsignedShortLE(6)));

        byte[] Call_Centor = new byte[20];
        bf.getBytes(8, Call_Centor);
        msg.setCall_Centor(byteArrToString(Call_Centor).trim());
        return msg;
    }

}
